/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checker.sdchecker;

import checker.sdchecker.unit.UnitFormatter;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author takeshi
 */
public class CheckResultObserver implements Observer {

    private JTextField files, bytes, elapsed, speed, remainingTime;

    private final AtomicBoolean queued = new AtomicBoolean();

    public CheckResultObserver(JTextField files, JTextField bytes, JTextField elapsed, JTextField speed, JTextField remainingTime) {
        this.files = files;
        this.bytes = bytes;
        this.elapsed = elapsed;
        this.speed = speed;
        this.remainingTime = remainingTime;
    }

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof TestResult) {
            TestResult r = (TestResult) arg;
            if(queued.compareAndSet(false, true)) {
                updateTestResult(r);
            }
            if(r.getCurrentFiles() == r.getTotalFiles()) {
                updateTestResult(r);
            }
        }
    }

    private void updateTestResult(final TestResult testResult) {
        Runnable run = new Runnable() {

            @Override
            public void run() {
                if (files != null) {
                    double perc = 100.0 * ((double) testResult.getCurrentFiles()) / testResult.getTotalFiles();
                    files.setText(testResult.getCurrentFiles() + "/" + testResult.getTotalFiles() + " " + String.format("%.2f", perc) + "%");
                }
                if (bytes != null) {
                    double perc = 100.0 * ((double) testResult.getCurrentBytes()) / testResult.getTotalBytes();
                    bytes.setText(testResult.getCurrentBytes() + "/" + testResult.getTotalBytes() + " " + String.format("%.2f", perc) + "%");
                }
                if (elapsed != null) {
                    elapsed.setText(UnitFormatter.formatTime(testResult.getTimeElapsed()));
                }
                if (speed != null) {
                    speed.setText(UnitFormatter.formatSpeed(testResult.getSpeed()));
                }
                if (remainingTime != null) {
                    remainingTime.setText(UnitFormatter.formatTime(testResult.remaining()));
                }
                queued.set(false);
            }
        };
        SwingUtilities.invokeLater(run);
    }
}
